package com.easy.controller;

import com.easy.bean.Product;
import com.easy.service.ProductService;
import com.easy.util.Page;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    ProductService productService;

    // 新增产品
    @PostMapping
    public Result add(@RequestBody Product product) {
        return Result.success(productService.add(product));
    }

    // 编辑产品
    @PutMapping("/{id}")
    public Result edit(@PathVariable("id") Integer id, @RequestBody Product product) {
        product.setId(id);
        return Result.success(productService.edit(product));
    }

    // 删除产品
    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id") Integer id) {
        return Result.success("删除成功", productService.del(id));
    }

    // 查询所有产品（可模糊查询）
    @GetMapping
    public Result all(
            @RequestParam(name = "name", required = false, defaultValue = "") String name,
            @RequestParam(name = "category", required = false, defaultValue = "") String category
    ) {
        return Result.success(productService.all(name, category));
    }

    // 查询单个产品
    @GetMapping("/{id}")
    public Result one(@PathVariable("id") Integer id) {
        return Result.success(productService.one(id));
    }

    // 分页查询
    @GetMapping("/page")
    public Result page(Page page, Product product) {
        productService.page(page, product);
        return Result.success(page);
    }
}
